package cn.zhouchao.org.service.impl;

import cn.zhouchao.basic.query.BaseQuery;
import cn.zhouchao.basic.util.BaiduAuditUtils;
import cn.zhouchao.basic.util.BusinessException;
import cn.zhouchao.basic.util.EmailUtil;
import cn.zhouchao.basic.util.PageList;
import cn.zhouchao.org.domain.Employee;
import cn.zhouchao.org.domain.Shop;
import cn.zhouchao.org.domain.ShopAuditLog;
import cn.zhouchao.org.dto.SettlementAgainDto;
import cn.zhouchao.org.dto.ShopRegisterDto;
import cn.zhouchao.org.dto.shopAuditLogDto;
import cn.zhouchao.org.mapper.EmployeeMapper;
import cn.zhouchao.org.mapper.ShopAuditLogMapper;
import cn.zhouchao.org.mapper.ShopMapper;
import cn.zhouchao.org.service.IShopService;
import cn.zhouchao.basic.service.impl.BaseServiceImpl;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhouchao
 * @since 2023-02-28
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private ShopAuditLogMapper shopAuditLogMapper;

    /**
     * 重写【分页业务】
     * @param Query
     * @return
     */
//    @Override
//    public PageList<Shop> queryByPage(BaseQuery Query) {
//        //========================重写内容============================
//        // 查询 条数
//        Integer totals = shopMapper.queryByCount(Query);
//        if (totals <= 0){
//            return new PageList<>(0,new ArrayList<>());
//        }
//        // 查询 数据
//        List<Shop> rows = shopMapper.queryByPage(Query);
//        List<Long> shopIds = new ArrayList<>();
//
//        for (Shop sh:rows){
//            shopIds.add(sh.getId());
//        }
//        // 根据shop的id 去查询所有的日志
//
//        List<ShopAuditLog> logs = shopAuditLogMapper.findByShopId(shopIds);
//        // 把他们两个关系拼接上  map 的key：shopId value ：日志的集合
//        Map<Long,List<ShopAuditLog>> logMap = new HashMap<>();
//        // 这个map是为了去除双重for循环
//        for (ShopAuditLog log : logs) {
//            // 先去获取一次
//            List<ShopAuditLog> shopAuditLogs = logMap.get(log.getShopId());
//            // 如果集合是空的 我们需要自己new一个 不然会报空指针
//            if (CollectionUtils.isEmpty(shopAuditLogs)){
//                shopAuditLogs = new ArrayList<>();
//            }
//            shopAuditLogs.add(log);
//            logMap.put(log.getShopId(),shopAuditLogs);
//        }
//
//        for (Shop sh : rows) {
//            List<ShopAuditLog> shopAuditLogs = logMap.get(sh.getId());
//            sh.setShopAuditLogs(shopAuditLogs);
//        }
//        //====================================================
////        //======================新业务(将日志数据装入店铺查询数据中并返回)==(联想无限极树)============================
////        //0.new 一个装shopIds的ArrayList集合，再遍历，并取rows里面的shop的id，加入进去
////        List<Long> shopId = new ArrayList<>();
////        for (Shop sh : rows) {
////            shopId.add(sh.getId());
////        }
////        //1.查询出所有的日志的通过shopId，即：findByShopId(),返回一个日志集合（一对多的关系）
////        List<ShopAuditLog> Logs = shopAuditLogMapper.findByShopId(shopId);
////        //2.new一个HashMap并用Map来接收，名为logMap的<key:shopId(Long), value:shopAuditLog>
////        Map<Long,List<ShopAuditLog>> logMap = new HashMap<>();
////        //3.增强for遍历出上面已经查询出来的shopAuditLogs日志集合
////        for (ShopAuditLog log : Logs) {
////            //3.1再一次去获取logMap中的values名为shopAuditLogs（即日志对象），通过日志的shopId,
////            List<ShopAuditLog> shopAuditLogs = logMap.get(log.getShopId());
////            //3.2空集合判断
////            if (CollectionUtils.isEmpty(shopAuditLogs)){
////                //3.2.1如果是空集合，就对value的里面装一个new的ArrayList空集合（new一个 不然会报空指针）赋值给shopAuditLogs
////                shopAuditLogs = new ArrayList<>();
////            }
////            //3.3将遍历后的日志对象依次add装入shopAuditLogs集合中
////            shopAuditLogs.add(log);
////            //3.4再将已经单独装好的集合装入Map<key:log.getShopId, value:shopAuditLogs集合>
////            logMap.put(log.getShopId(),shopAuditLogs);
////        }
////        //4.增强for遍历原有的分页查询的rows数据 别名sh
////        for (Shop sh : rows) {
////            //4.1通过logMap去获取店铺审核日志集合 （条件是通过调sh遍历后对象的id）
////            List<ShopAuditLog> shopAuditLogs = logMap.get(sh.getId());
////            //4.2将对遍历后的对象，每个进行设置店铺日志审核对象集合
////            sh.setShopAuditLogs(shopAuditLogs);
////        }
////        //====================================================
//        /*返回分页条数+修改后的分页数据*/
//        return super.queryByPage(Query);
//    }

    // 注入邮件对象
    @Autowired
    private JavaMailSender javaMailSender;

    /*批量添加*/
    public void batchAddShop(List<Shop> ShopList){
        shopMapper.batchAddShop(ShopList);
    }

    //店铺入驻业务
    @Override
    public void settlement(ShopRegisterDto dto) {
        //参数校验
        verify(dto);
        //添加到数据库
        save(dto);

    }

    /**
     * 店铺重新入驻业务
     * @param dto
     */
    @Override
    public void settlementAgain(ShopRegisterDto dto) {
        /*再次参数校验*/
        verifyAgain(dto);
        /*修改数据*/
        update(dto);
    }

    /***
     * 修改数据
     * @param dto
     */
    private void update(ShopRegisterDto dto) {
        //修改数据
        Shop shop = new Shop();
        shop.setId(dto.getId());
        shop.setName(dto.getName());
        shop.setTel(dto.getTel());
        shop.setAddress(dto.getAddress());
        shop.setLogo(dto.getLogo());
        shop.setState(0);//驳回后修改状态为待审核
        shopMapper.update(shop);//执行修改数据
    }

    /**
     * 再次参数校验
     * @param dto
     */
    private void verifyAgain(ShopRegisterDto dto) {
        //1.1判断店铺是否已经存在(通过【店铺名】以及【店铺地址】)
        Shop shop1 = shopMapper.findShopByNmaeAndAddress(dto.getName(), dto.getAddress());
        if (null != shop1){
            throw new BusinessException("该店铺已经存在！");
        }
        //2、AI审核
        //判断店铺名是否违规
        Boolean textCensor = BaiduAuditUtils.TextCensor(dto.getName());
        if (!textCensor){
            throw new BusinessException("店铺名违规！");
        }
        //判断店铺名logo是否违规
        Boolean ImgaeCensor = BaiduAuditUtils.ImgCensor(dto.getLogo());//true
        if (!ImgaeCensor){
            throw new BusinessException("店铺logo违规！");
        }
    }

    /**
     * 人工审核通过
     * @param dto
     */
    @Override
    public void auditPass(shopAuditLogDto dto){
        //拼接使用?shopId=...
        //1.修改店铺状态
        Shop shop1 = new Shop();
        Long shopId = dto.getShopId();
        //设置shop的id(便于修改shop状态)
        shop1.setId(shopId);
        shop1.setState(2);//审核通过就修改【待审核状态：0】为【待激活状态：2】
        shopMapper.update(shop1);//执行修改
        //2.添加审核日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        String note = dto.getNote();
        shopAuditLog.setNote(note);
        shopAuditLog.setShopId(shopId);
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setAuditId(-1);
        shopAuditLogMapper.add(shopAuditLog);
        //2.发送邮件
        EmailUtil.getEmail("<h1>恭喜您，店铺审核通过！请点击下方链接进行店铺激活：</h1>"
                +"http://localhost:8080/shop/activity/"+dto.getShopId(),true);
//        try {
//            // 1.创建复杂邮件对象
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            // 2.发送复杂邮件的工具类
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("1913996712@qq.com");
//            helper.setSubject("店铺审核通知");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>恭喜您，店铺审核通过！请点击下方链接进行店铺激活：</h1>"
//                    +"http://localhost:8080/shop/activity/"+dto.getShopId(),true);
//            // 4.添加附件
//            helper.addAttachment("好东西.jpg",new File("C:\\Users\\Administrator\\Desktop\\2.jpg"));
//            // 5.设置收件人
//            helper.setTo("2909457237@qq.com");
//            // 6.发送邮件
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }

    }

    /**
     * 店铺激活
     * @param shopId
     */
    @Override
    public void activity(Long shopId) {
        Shop shop = new Shop();
        shop.setId(shopId);
        shop.setState(1);
        shopMapper.update(shop);
    }

    /**
     * 人工审核驳回
     * @param dto
     */
    @Override
    public void reject(shopAuditLogDto dto) {
        //拼接使用?shopId=...
        //1.修改店铺状态
        Shop shop1 = new Shop();
        Long shopId = dto.getShopId();
        //设置shop的id(便于修改shop状态)
        shop1.setId(shopId);
        shop1.setState(3);//审核通过就修改【待审核状态：0】为【待激活状态：2】
        shopMapper.update(shop1);//执行修改
        //2.添加审核日志
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        String note = dto.getNote();
        shopAuditLog.setNote(note);
        shopAuditLog.setShopId(shopId);
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setAuditId(-1);
        shopAuditLogMapper.add(shopAuditLog);

        //2.发送邮件
        EmailUtil.getEmail("<h1>抱歉，店铺审核不通过！请点击下方链接修改店铺入驻信息：</h1>"
                +"http://localhost:8081/#/RegisterAgain?shopId="+dto.getShopId(),true);
//        try {
//            // 1.创建复杂邮件对象
//            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//            // 2.发送复杂邮件的工具类
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
//            helper.setFrom("1913996712@qq.com");
//            helper.setSubject("店铺审核通知");
//            // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
//            helper.setText("<h1>抱歉，店铺审核不通过！请点击下方链接修改店铺入驻信息：</h1>"
//                    +"http://localhost:8081/#/RegisterAgain?shopId="+dto.getShopId(),true);
//            // 4.添加附件
//            helper.addAttachment("好东西.jpg",new File("C:\\Users\\Administrator\\Desktop\\3.jpg"));
//            // 5.设置收件人
//            helper.setTo("2909457237@qq.com");
//            // 6.发送邮件
//            javaMailSender.send(mimeMessage);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//        }

    }

    /**
     * 参数校验
     * @param dto
     */
    private void verify(ShopRegisterDto dto) {
        //1.0
        // 1.5手机号验证
        Pattern p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
        Matcher m = p.matcher(dto.getAdmin().getPhone());
        if (!m.matches()){
            throw new BusinessException("用户手机号格式不正确！");
        }
        //1.3判断该用户是否已经拥有店铺了()
        Employee emp = employeeMapper.findEmpByName(dto.getAdmin().getUsername());
        if (null != emp && null != emp.getShopId()){// 先判断是否存在该用户，以及他是否有shopId
            Shop shop1 = shopMapper.findAdminByEmpId(emp.getId());
            if (null != shop1){//判断是否是店长，即有无adminId
                throw new BusinessException("您已经存在店铺，请前往登录界面进行登录！");
            }
        }
        //1.3判断两次密码是否相等
        if (!dto.getAdmin().getPassword().equals(dto.getAdmin().getComfirmPassword())){
            throw new BusinessException("两次密码不一致！");
        }
        //1.1判断店铺是否已经存在(通过【店铺名】以及【店铺地址】)
        Shop shop = shopMapper.findShopByNmaeAndAddress(dto.getName(), dto.getAddress());
        if (null != shop){
            throw new BusinessException("该店铺已经存在！");
        }
        //2、AI审核
        //判断店铺名是否违规
        Boolean textCensor = BaiduAuditUtils.TextCensor(dto.getName());
        if (!textCensor){
            throw new BusinessException("店铺名违规！");
        }
        //判断店铺名logo是否违规
        Boolean ImgaeCensor = BaiduAuditUtils.ImgCensor(dto.getLogo());//true
        if (!ImgaeCensor){
            throw new BusinessException("店铺logo违规！");
        }
    }

    /**
     * 添加数据库
     * @param dto
     */
    private void save(ShopRegisterDto dto) {
        //3、添加到数据库
        //3.1添加shop数据
        Shop shop3 = dto.getShop();
        shopMapper.add(shop3);
        //3.2获取最新员工对象
        Employee emp1 = dto.getEmp();
        //3.3将shopId直接设置进去
        emp1.setShopId(shop3.getId());
        //3.4调用add方法添加员工
        employeeMapper.add(emp1);
        //3.5.添加AdminId
        //3.5.1创建一个空对象（因为要修改数据，所以以新对象设置单个值进行修改）
        Shop shop4 = new Shop();
        //3.5.2入驻的shop的id赋值给空对象
        shop4.setId(shop3.getId());
        //3.5.3并将入职的店长的员工id赋值给新shop对象，进行值得修改
        shop4.setAdminId(emp1.getId());
        //3.5.4调用修改方法
        shopMapper.update(shop4);
    }


}
